<template>
  <view class="tui-skeleton order-details">
    <l-background has-sub-background />

    <template>
      <view id="tab" class="padding-top-30 padding-lr-30">
        <l-tab-bar v-if="newObj.orderType == 0 || newObj.orderType == 1" type="2" :tabs="tabList" />
		<l-tab-bar v-else type="2" :tabs="tabList" :active-inx.sync="tabInx" />
      </view>

      <scroll-view scroll-y :style="{height:height+'px'}">
		  <view class="padding-lr-30 padding-bottom-30" v-if="newObj.orderType == 0 || newObj.orderType == 1">
		    <order-info :orderType="1" :order-info="objInfo" />
		    <client-info :orderType="1" :order-info="objInfo" :stop-show="stopShow" :call-phone="callPhone" />
		  </view>
        <view v-else class="padding-lr-30 padding-bottom-30">
          <order-info  :order-info="newObj" />
          <client-info  :order-info="orderInfo" :stop-show="stopShow" :call-phone="callPhone" />

          <vehicle-info :orderType="1" :order-info="orderInfo" />

          <mileage-info :orderType="1" :order-info="orderInfo" />
        </view>
      </scroll-view>
	 <view class="btn-list">
	 	<view class="grabasingle" v-if="newObj.orderType == 0" @click="goRobOrder(newObj)">
	 		立即抢单
	 	</view>
		<view class="distribution-order" v-if="newObj.orderType == 1" @click="goDrive(newObj)">
			分配订单
		</view>
	 </view>
      <!-- <related-fee v-show="tabInx" :height="height" :order-id="orderId" /> -->

      <!-- <safe-area-bottom v-show="!tabInx && showButton" id="safe-bottom" /> -->

      <!-- <l-bottom-button v-show="!tabInx && showButton" :show-button="false">
        <view class="flex-row justify-end">
          <view
            v-for="(item, index) in showButtons"
            :key="index"
            class="flex-item"
            :class="{'margin-right-20':index !== showButtons.length - 1}"
          >
            <tui-button height="80rpx" :size="30" :shadow="false" :plain="index !== showButtons.length - 1" :type="index !== showButtons.length - 1 ? 'gray' :'primary'" @click="buttonClick(item.methods,item.params)">{{ item.text }}</tui-button>
          </view>
        </view>
      </l-bottom-button> -->
    </template>

    <!-- <hook-detail v-else :order-info="orderInfo" /> -->

    <!-- <tui-modal :show.sync="show" title="提示" :content="content" @click="modalClick" /> -->

    <!-- <tui-modal :show.sync="showConfirmOrder" title="确认订单" content="确认订单后将通知司机和客户，请确保司机和车辆能够为客户提供服务。" :button="button" @click="confirmOrder" /> -->

    <!-- <tui-skeleton v-if="showSkeleton" :preload-data="preloadData" /> -->
  </view>
</template>

<script>
import OrderInfo from '../components/order-info/order-info'
import ClientInfo from '../components/client-info/client-info'
import VehicleInfo from '../components/vehicle-info/vehicle-info'
import MileageInfo from '../components/mileage-info/mileage-info'
import RelatedFee from '../components/related-fee/related-fee'
import HookDetail from '../components/hook-detail/hook-detail'
import { mapGetters } from 'vuex'
import { loading, cellPhone } from '@/common/util'
import { getOrderDetail, cancelOrder, getPhone, delOrder } from '../api'
	import {companyGrabOrders, getCarpoolTakeOrderStatus, setCarpoolTakeOrderStatus, driverSubsidyProportionPage, setDriverSubsidyProportion, grabOrderPage,pageOrderRecord } from '@/common/api/driver.js'
import { orderTrackStart, finishOrder, reviewOrder, getHookOrderDetail, lockOrder ,grabOrderDetail} from '@/common/api/order'
import { preloadData } from './index'
import $http from '../../common/api/request'
export default {
  name: 'OrderDetail',
  components: {
    OrderInfo,
    ClientInfo,
    VehicleInfo,
    MileageInfo,
    RelatedFee,
    HookDetail
  },
  data() {
    return {
      tabInx: 0,
      tabList: [
        { title: '订单详情' },
        { title: '关联费用' }
      ],
      type: 'order',
      orderId: '',
      orderInfo: {},
      stopShow: '',
      showCall: false,
      callPhone: '',
      showSkeleton: true,
      preloadData,
      content: '',
      modalType: 0,
      show: false,
      showConfirmOrder: false,
      button: [
        {
          text: '取消',
          type: 'gray'
        },
        {
          text: '确认订单'
        }
      ],
      height: 0,
      bottomHeight: 0,
	  newObj:{},
	  objInfo:{}
    }
  },
  computed: {
    buttons() {
      return [
        { text: '编辑', show: this.auth.includes('charter_order_remarks') && (this.orderInfo.status === 3 || (this.orderInfo.status === 8 && this.orderInfo.ioType === 0) || (this.orderInfo.ioType && this.orderInfo.isLock && this.orderInfo.status === 8) || this.orderInfo.status === 10), methods: 'editOrder', params: 'remark' },
        { text: '编辑', show: ((this.orderInfo.status === 2 || this.orderInfo.status === 4 || this.orderInfo.status === 6 || this.orderInfo.status === 9 || this.orderInfo.status === 7) || (this.orderInfo.ioType && this.orderInfo.status === 1) || (this.orderInfo.ioType && !this.orderInfo.isLock && this.orderInfo.status === 8 && this.auth.includes('charter_order_lock'))) && this.auth.includes('charter_order_edit'), methods: 'editOrder', params: 'order' },
        { text: '锁单', show: this.orderInfo.ioType && !this.orderInfo.isLock && this.orderInfo.status === 8 && this.auth.includes('charter_order_lock'), methods: 'showModal', params: 3 },
        { text: '删除订单', show: this.orderInfo.ioType && this.auth.includes('charter_order_delete'), methods: 'showModal', params: 2 },
        { text: '取消订单', show: (this.orderInfo.status === 1 || this.orderInfo.status === 2 || this.orderInfo.status === 4 || this.orderInfo.status === 6) && this.orderInfo.ioType && this.auth.includes('charter_order_cancel'), methods: 'showModal', params: 1 },
        // { text: '转单', show: (this.orderInfo.status === 1 || this.orderInfo.status === 2 || this.orderInfo.status === 4 || this.orderInfo.status === 6) && this.auth.includes('charter_order_transfer') && !this.orderInfo.ioType, methods: 'handleGoVehicleSelector', params: null },
        { text: '联系导游', show: !this.orderInfo.ioType && (this.orderInfo.status === 6 || this.orderInfo.status === 4 || ((this.orderInfo.status === 8 || this.orderInfo.status === 7) && this.showCall)) && this.auth.includes('charter_order_guide'), methods: 'call', params: null },
        { text: '确认订单', show: (this.orderInfo.status === 1 && this.orderInfo.payWay !== 1) || this.orderInfo.status === 2 && this.auth.includes('charter_order_confirm'), methods: 'showConfirmOrderModel', params: null },
        { text: '开始行程', show: this.orderInfo.status === 4 && this.auth.includes('start_stroke'), methods: 'startTrip', params: null },
        { text: '结束行程', show: this.orderInfo.status === 6 && this.auth.includes('start_stroke'), methods: 'showModal', params: 0 },
		
      ]
    },
    showButtons() {
      const arr = []
      this.buttons.forEach(item => {
        if (item.show) arr.push(item)
      })
      return arr
    },
    showButton() {
      return this.showButtons.length
    },
    ...mapGetters({
      auth: 'auth'
    })
  },
  watch: {
    tabInx(e) {
      if (this.showButton) {
        if (e) {
          this.height += this.bottomHeight
        } else {
          this.height -= this.bottomHeight
        }
      }
    },
  },
  onLoad(e) {
    this.orderId = e.orderId
    this.type = e.type
	this.newObj = JSON.parse(e.obj)
	this.newObj.realPrice = this.newObj.totalPrice
	// console.log(e.obj);
	if(this.newObj.orderType == 0 || this.newObj.orderType == 1){
		this.tabList = [
        { title: '订单详情' },
        { title: '' }
      ],
		this.getInfoList(this.newObj)
	}
	// else if(this.newObj.orderType == 2){
	// 	this.getOldInforList(this.newObj)
	// }else{
		
	// }
	// console.log(this.newObj)
  },
  onShow() {
    // if (this.type === 'order') this.getOrderDetail()
    // else this.getHookDetail()
  },
  mounted() {
    this.init()
  },
  methods: {
	  async goRobOrder(data){
	  	let [err,res] = await companyGrabOrders(data.orderId)
		if(res.data.code == -1){
			uni.showToast({
			    title: res.data.msg,
			    duration: 1000,
				icoicon:'none',
				})
					return
		}
	
		 data.assignVehicleScountDown = res.data.data
	  	if(res.data.data){
	  		uni.navigateTo({
	  			url:'/order/rob-order/rob-order?person=' + JSON.stringify(data),
	  		})
	  	}else{
	  		uni.showToast({
	  		    title: '抢单失败',
				icon:'none',
	  		    duration: 1000
	  			})
	  	}
	  },
	  async goDrive(item){
	  	if(!item.orderId){
	  		item.orderId = item.id
	  	}
	  	uni.navigateTo({
	  		url:'/order/rob-order/rob-order?person=' + JSON.stringify(item),
	  	})
	  },
	  async getOldInforList(data){
		  await this.getOrderDetailCv(data)
	  },
	  async getOrderDetailCv(data) {
	    const [err, res] = await getOrderDetail(data.orderId)
	    this.showSkeleton = false
	    if (!this.$http.errorCheck(err, res)) return false
	    const orderInfo = res.data.data
	    // orderInfo.stopSite=['地址1|116.481028|39.989643','地址2|116.12228|39.98121233','地址3|113.121228|32.12643'];
	    if (orderInfo.stopSite) {
	      const arr = []
	      const stopArr = orderInfo.stopSite.split(',')
	      for (let i = 0; i < stopArr.length; i++) {
	        const siteArr = stopArr[i].split('|')
	        arr.push(siteArr[0])
	      }
	      this.stopShow = arr.join('——')
	    }
	    this.orderInfo = orderInfo
	    const twoDay = 1000 * 60 * 60 * 24 * 2
	    const endDate = new Date(orderInfo.endDate).getTime() + twoDay
	    const now = new Date().getTime()
	    this.showCall = !!(orderInfo.status == 6 || orderInfo.status == 4 || ((orderInfo.status == 8 || orderInfo.status == 7) && now < endDate))
	    if (orderInfo.ioType) {
	      this.callPhone = orderInfo.phone
	    }
	  },
	  async getInfoList(data){
		 let [err,res] = await grabOrderDetail(data.orderId)
		 console.log(res.data.data)
		 this.objInfo = res.data.data
		 this.objInfo.realPrice = this.objInfo.totalPrice
	  },
    async init() {
      // await this.getOrderDetail()
      this.getHeight()
    },
    getHeight() {
      const wHeihgt = this.sysInfo().windowHeight
      this.getElementInfo('#tab', res => {
        this.height = wHeihgt - res.height
        this.getElementInfo('#safe-bottom', res => {
          this.bottomHeight = res.height + this.px(120)
          if (this.showButton) {
            this.height -= this.bottomHeight
          }
        })
      })
    },
    async getOrderDetail() {
      const [err, res] = await getOrderDetail(this.orderId)
      this.showSkeleton = false
      if (!this.$http.errorCheck(err, res)) return false
      const orderInfo = res.data.data
      // orderInfo.stopSite=['地址1|116.481028|39.989643','地址2|116.12228|39.98121233','地址3|113.121228|32.12643'];
      if (orderInfo.stopSite) {
        const arr = []
        const stopArr = orderInfo.stopSite.split(',')
        for (let i = 0; i < stopArr.length; i++) {
          const siteArr = stopArr[i].split('|')
          arr.push(siteArr[0])
        }
        this.stopShow = arr.join('——')
      }
      this.orderInfo = orderInfo
      const twoDay = 1000 * 60 * 60 * 24 * 2
      const endDate = new Date(orderInfo.endDate).getTime() + twoDay
      const now = new Date().getTime()
      this.showCall = !!(orderInfo.status == 6 || orderInfo.status == 4 || ((orderInfo.status == 8 || orderInfo.status == 7) && now < endDate))
      if (orderInfo.ioType) {
        this.callPhone = orderInfo.phone
      }
    },
    async getPhone(data) {
      const [err, res] = await getPhone(data)
      if (!this.$http.errorCheck(err, res)) return false
      this.callPhone = res.data.data
    },
    buttonClick(m, p) {
      this[m](p)
    },
    async call() {
	if (!this.orderInfo.ioType) {
		await this.getPhone(this.orderId)
	} 
      cellPhone(this.callPhone)
    },
    // 开始行程
    async startTrip() {
      const l = loading('加载中')
      const [err, res] = await orderTrackStart({ orderId: this.orderId })
      l.hide()
      if (!this.$http.errorCheck(err, res)) return false
      this.toast('行程已开始')
      await this.getOrderDetail()
    },
    // 展示弹窗
    showModal(type) {
      switch (type) {
        case 0:
          this.content = '结束行程后将不可撤销，是否确定结束行程'
          break
        case 1:
          this.content = '是否确认取消订单'
          break
        case 2:
          this.content = this.orderInfo.hasDailyExpenditureBalance ? '该订单存在日常收支记录，是否删除该订单' : '是否删除该订单'
          break
        case 3:
          this.content = '锁单后将无法修改订单信息，是否确认锁单？'
          break
      }
      this.show = true
      this.modalType = type
    },
    // 弹窗点击事件
    modalClick(e) {
      this.show = false
      if (e.index) {
        switch (this.modalType) {
          case 0:
            this.finishOrder()
            break
          case 1:
            this.cancelOrder()
            break
          case 2:
            this.delOrder()
            break
          case 3:
            this.lockOrder()
            break
        }
      }
    },
    // 编辑
    editOrder(type) {
      this.jump('/order/edit/edit?type=' + type + '&orderId=' + this.orderId)
    },
    // 转单选择车辆
    handleGoVehicleSelector() {
      this.jump('/vehicle/list/index?type=transferOrder' +
          '&seatAmount=' + 'bt' + this.orderInfo.passengers +
          '&startDate=' + this.orderInfo.startDate +
          '&endDate=' + this.orderInfo.endDate +
          '&orderId=' + this.orderId)
    },
    showConfirmOrderModel() {
      this.showConfirmOrder = true
    },
    // 确认订单
    async confirmOrder(e) {
      this.showConfirmOrder = false
      if (e.index) {
        const l = loading('确认中')
        const [err, res] = await reviewOrder({
          orderId: this.orderId,
          status: 1
        })
        l.hide()
        if (!this.$http.errorCheck(err, res)) return false
        this.toast('确认成功')
        await this.getOrderDetail()
      }
    },
    // 结束订单
    async finishOrder() {
      const payWay = this.orderInfo.payWay
      const status = this.orderInfo.status
      let changeStatus
      if (status === 6 && payWay === 1)changeStatus = 8
      else if (status === 6 && payWay !== 1) changeStatus = 7

      const l = loading('加载中')
      const [err, res] = await finishOrder({
        orderId: this.orderId,
        status: changeStatus
      })
      l.hide()
      if (!this.$http.errorCheck(err, res)) return false

      this.toast('已结束该订单')
      await this.getOrderDetail()
    },
    // 取消订单
    async cancelOrder() {
      const l = loading('加载中')
      const [err, res] = await cancelOrder({
        orderId: this.orderId,
        cancelComment: '车企主动取消'
      })
      l.hide()
      if (!this.$http.errorCheck(err, res)) return false
      this.toast('取消订单成功')
      await this.getOrderDetail()
    },
    // 删除订单
    async delOrder() {
      const l = loading('加载中')
      const [err, res] = await delOrder({
        orderId: this.orderId
      })
      l.hide()
      if (!this.$http.errorCheck(err, res)) return false
      this.toast('删除订单成功')
      uni.navigateBack()
    },
    // 获取获客订单
    async getHookDetail() {
      const [err, res] = await getHookOrderDetail({
        id: this.orderId
      })
      this.showSkeleton = false
      if (!this.$http.errorCheck(err, res)) return false
      this.orderInfo = res.data.data
    },
    // 锁单
    async lockOrder(orderId) {
      const [err, res] = await lockOrder({
        orderId: this.orderId
      })
      if (!$http.errorCheck(err, res)) return false
      this.toast('锁单成功')
      await this.getOrderDetail()
    }
  }
}

</script>

<style scoped lang="scss">
.flex-item:last-child{
  flex:2;
}
.order-details{
	overflow-y: scroll;
	padding-bottom: 100rpx;
}
.btn-list{
	position: fixed;
	padding: 20rpx;
	bottom: 0;
	left: 0;
	width: 100vw;
	line-height: 100rpx;
	text-align: center;
	background-color: #fff;
	display: flex;
	justify-content: center;
	align-content: center;
	flex-direction: row;
	box-shadow: 0 -2rpx 10rpx #999;
	.grabasingle{
		width: fit-content;
		height: fit-content;
		border-radius: 10rpx;
		padding: 20rpx 20rpx;
		font-size: 32rpx;
		font-weight: 600;
		    background-image: linear-gradient(to right, #f2c790, #daa665) !important;
		    color: #7A5032;
		border-radius: 10rpx;
		border: 2rpx solid #999;
		letter-spacing: 2rpx;
	}
	.distribution-order{
		height: fit-content;
		width: fit-content;
		padding: 20rpx 30rpx;
		font-size: 32rpx;
		font-weight: 600;
		color: #fff;
		background-image: linear-gradient(to right, #efc690, #dcaa6b);
		border-radius: 10rpx;
		border: 2rpx solid #fff;
		letter-spacing: 2rpx;
	}
}
</style>
